/**
 * Copyright 2011 Joao Miguel Pereira
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package eu.jpereira.trainings.designpatterns.creational.builder.json;

import java.util.Iterator;

import eu.jpereira.trainings.designpatterns.creational.builder.model.ReportBody;
import eu.jpereira.trainings.designpatterns.creational.builder.model.SaleEntry;
import eu.jpereira.trainings.designpatterns.creational.builder.model.SoldItem;

/**
 * For training purposes only!
 * 
 * @author jpereira
 *
 */
public class JSONReportBody implements ReportBody {

        private StringBuilder stringBuilder = new StringBuilder();

        /*
         * (non-Javadoc)
         * 
         * @see eu.jpereira.trainings.designpatterns.creational.builder.ReportBody#
         * getAsString()
         */
        @Override
        public Object getAsString() {
                return this.stringBuilder.toString();
        }

        /**
         * @param content
         */
        public void addContent(Object content) {
                stringBuilder.append(content);

        }

        @Override
        public void content(ReportBody rb, SaleEntry saleEntry) {

                rb.addContent("sale:{customer:{");
                rb.addContent("name:\"");
                rb.addContent(saleEntry.getCustomer().getName());
                rb.addContent("\",phone:\"");
                rb.addContent(saleEntry.getCustomer().getPhone());
                rb.addContent("\"}");
                rb.addContent(",items:[");

        }

        @Override
        public void iterate(ReportBody rb, SaleEntry saleEntry) {

                Iterator<SoldItem> it = saleEntry.getSoldItems().iterator();

                while (it.hasNext()) {
                        SoldItem item = it.next();
                        rb.addContent("{name:\"");
                        rb.addContent(item.getName());
                        rb.addContent("\",quantity:");
                        rb.addContent(String.valueOf(item.getQuantity()));
                        rb.addContent(",price:");
                        rb.addContent(String.valueOf(item.getUnitPrice()));
                        rb.addContent("}");
                        if (it.hasNext()) {
                                rb.addContent(",");
                        }

                }
                rb.addContent("]}");

        }

}
